package com.generator.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.S3ClientBuilder;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;

import java.io.File;
import java.net.URI;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 云存储服务（支持S3协议）
 * 
 * @author Generator
 * @since 2024-01-01
 */
@Service
public class CloudStorageService {
    
    @Value("${cloud.storage.s3.endpoint:}")
    private String s3Endpoint;
    
    @Value("${cloud.storage.s3.access-key:}")
    private String accessKey;
    
    @Value("${cloud.storage.s3.secret-key:}")
    private String secretKey;
    
    @Value("${cloud.storage.s3.bucket:}")
    private String bucketName;
    
    @Value("${cloud.storage.s3.region:us-east-1}")
    private String region;
    
    @Value("${cloud.storage.enabled:false}")
    private boolean storageEnabled;
    
    /**
     * 上传文件到云存储
     * 
     * @param file 要上传的文件
     * @param fileName 文件名
     * @return 下载链接
     */
    public String uploadFile(File file, String fileName) {
        if (!storageEnabled || !isConfigured()) {
            throw new RuntimeException("云存储未配置或未启用");
        }
        
        try {
            S3Client s3Client = createS3Client();
            
            // 生成带时间戳的文件名
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
            String objectKey = "generated-code/" + timestamp + "_" + fileName;
            
            PutObjectRequest putObjectRequest = PutObjectRequest.builder()
                    .bucket(bucketName)
                    .key(objectKey)
                    .contentType("application/zip")
                    .build();
            
            s3Client.putObject(putObjectRequest, RequestBody.fromFile(file));
            
            // 构建下载链接
            String downloadUrl;
            if (s3Endpoint != null && !s3Endpoint.isEmpty()) {
                // 自定义端点（如MinIO）
                downloadUrl = s3Endpoint + "/" + bucketName + "/" + objectKey;
            } else {
                // AWS S3
                downloadUrl = String.format("https://%s.s3.%s.amazonaws.com/%s", 
                    bucketName, region, objectKey);
            }
            
            return downloadUrl;
            
        } catch (Exception e) {
            throw new RuntimeException("文件上传失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 创建S3客户端
     */
    private S3Client createS3Client() {
        S3ClientBuilder builder = S3Client.builder()
                .region(Region.of(region))
                .credentialsProvider(StaticCredentialsProvider.create(
                    AwsBasicCredentials.create(accessKey, secretKey)));
        
        // 如果有自定义端点，设置端点URI
        if (s3Endpoint != null && !s3Endpoint.isEmpty()) {
            builder.endpointOverride(URI.create(s3Endpoint));
        }
        
        return builder.build();
    }
    
    /**
     * 检查是否已配置
     */
    private boolean isConfigured() {
        return accessKey != null && !accessKey.isEmpty() &&
               secretKey != null && !secretKey.isEmpty() &&
               bucketName != null && !bucketName.isEmpty();
    }
    
    /**
     * 检查云存储是否可用
     */
    public boolean isAvailable() {
        return storageEnabled && isConfigured();
    }
}